package com.jia.netty.listener;

import com.google.gson.Gson;
import com.jia.entity.netty.ChartMsg;
import com.jia.entity.netty.ShutDownMsg;
import com.jia.netty.channel.ChannelGroup;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "ws_queue_${netty.port}")
public class WsQueueListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitHandler
    public void wsMsg(ShutDownMsg shutDownMsg) {
        String did = shutDownMsg.getDid();
        Channel channel = ChannelGroup.getChannel(did);
        if (channel != null) {
            TextWebSocketFrame resp = new TextWebSocketFrame(new Gson().toJson(shutDownMsg));
            channel.writeAndFlush(resp);
        }
    }

    @RabbitHandler
    public void wsChart(ChartMsg chartMsg) {
        // 根据tid查询did
        String did = redisTemplate.opsForValue().get(chartMsg.getTid());
        Channel channel = ChannelGroup.getChannel(did);
        if (channel != null) {
            TextWebSocketFrame resp = new TextWebSocketFrame(new Gson().toJson(chartMsg));
            channel.writeAndFlush(resp);
        }
    }

}
